<template>
  <span style="margin-left: 10px; color: #f56c6c">{{ formattedTime }}</span>
</template>

<script>
export default {
  data() {
    return {
      endTime: 0,
      timeLeft: 0, // 以秒为单位
      timer: null,
    };
  },
  props: {
    saveTime: {
      type: Number,
      default: 3600,
    },
  },
  computed: {
    formattedTime() {
      const hours = Math.floor(this.timeLeft / 3600);
      const minutes = Math.floor((this.timeLeft % 3600) / 60);
      const seconds = this.timeLeft % 60;

      return `${hours.toString().padStart(2, "0")}:${minutes
        .toString()
        .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    },
  },
  methods: {
    startCountdown(duration) {
      const now = Date.now();
      this.endTime = now + duration * 1000;
      localStorage.setItem("countdownEndTime", this.endTime);
      this.tick();
    },
    tick() {
      const now = Date.now();
      this.timeLeft = Math.round((this.endTime - now) / 1000);

      if (this.timeLeft <= 0) {
        this.timeLeft = 0;
        clearTimeout(this.timer);
        localStorage.removeItem("countdownEndTime");
        this.$emit("countdownFinished");
        return;
      }

      // 每次调用tick后，设置下一次调用的延迟时间为1000毫秒（1秒）
      this.timer = setTimeout(this.tick, 1000);
    },
    clearTime() {
      clearTimeout(this.timer);
      localStorage.removeItem("countdownEndTime");
    },
    init() {
      const savedEndTime = localStorage.getItem("countdownEndTime");
      if (savedEndTime) {
        this.endTime = parseInt(savedEndTime, 10);
        if (this.endTime > Date.now()) {
          this.tick();
        } else {
          localStorage.removeItem("countdownEndTime");
        }
      } else {
        // 这里设置倒计时的时长，例如3600秒（1小时）
        console.log("res", this.saveTime);
        this.startCountdown(this.saveTime);
      }
    },
  },
  created() {},
  beforeDestroy() {
    clearTimeout(this.timer);
  },
};
</script>
